<?php
/**
 * helper_uploader 
 * 
 * @package moBlog-lite 
 * @version $Id$
 * @copyright 2007 - 2009 Movoin.com Ltd.
 * @author allen <movoin@gmail.com> 
 * @explanation 
 *      上传目录：年份-月份/图片名称
 */
class helper_uploader
{
    var $_uploader; 
    var $_file;
    var $_uploadDir;
    
    /**
     * helper_uploader 构造函数 
     * 
     * @param mixed $file 
     * @param string $server 
     * @access public
     * @return void
     */
    function helper_uploader($file, $server = 'local') {
        /**
         * 载入上传助手
         */
        FLEA::loadClass('FLEA_Helper_FileUploader');
        $this->_uploader =& new FLEA_Helper_FileUploader();
        /**
         * 接收文件句柄
         */
        $this->_file = $file;
        /**
         * 上传目录
         */
        $this->_uploadDir = FLEA::getAppInf('uploadDir');
    }

    /**
     * 上传图片文件
     */
    function uploadImage() {
        $_error = 0; //错误信息
        /**
         * 判断文件是否存在，并检查是否为图片文件 
         */
        if ( $this->_uploader->isFileExist($this->_file) )
        {
            dump($this->_file);
            $postfile = $this->_uploader->getFile($this->_file);
            if ( !$postfile->check('.jpg/.gif/.png') )
            {
                $_error = 'Picture format is not right!';
            }
            $_pic = $this->_upload($postfile);
        }

        return array(
                'uploadDir' => $_pic['uploadDir'],
                'filename' => $_pic['filename'],
                'error' => $_error,
            );
    }

    /**
     * _upload 上传文件
     * 
     * @param mixed $postfile 
     * @access protected
     * @return void
     */
    function _upload($postfile) {
        /**
         * 按日期创建上传目录 
         */
        $prefix = date('y-m');
        $dirname = $this->_uploadDir . DS . $prefix;
        FLEA::loadFile('FLEA_Helper_FileSystem');
        mkdirs($dirname);
        
        /**
         * 设置上传文件名称 
         */
        $basename = md5(time() . $postfile->getTmpName()) . '.' . strtolower($postfile->getExt());
        /**
         * 上传文件 
         */
        $postfile->move($dirname . DS . $basename);
        /**
         * 返回结果 
         */
        return array(
                'uploadDir' => FLEA::getAppInf('uploadPath') . $prefix . '/',
                'filename' => $basename,
            );
    }

}
